package com.mornd.gulimall.order.config.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author: mornd
 * @dateTime: 2023/8/28 - 7:15
 * 支付宝支付
 */

@Slf4j
@Component
@EnableConfigurationProperties(AlipayProperties.class)
public class AlipayTemplate {

    private final AlipayProperties alipayProperties;

    private static String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static String FORMAT = "json";
    private static String CHARSET = "utf-8";
    private static String SIGN_TYPE = "RSA2";

    public AlipayTemplate(AlipayProperties alipayProperties) {
        this.alipayProperties = alipayProperties;
    }

    /**
     * PC场景下单并支付
     *
     * @param aliPay
     * @return
     * @throws AlipayApiException
     */
    public String pay(AliPay aliPay) throws AlipayApiException {
        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayProperties.getGatewayUrl(),
                alipayProperties.getAppId(),
                alipayProperties.getAppPrivateKey(),
                alipayProperties.getFormat(),
                alipayProperties.getCharset(),
                alipayProperties.getAlipayPublicKey(),
                alipayProperties.getSignType());

        // 2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

        request.setNotifyUrl(alipayProperties.getNotifyUrl());
        request.setReturnUrl(alipayProperties.getReturnUrl());

        aliPay.setProduct_code("FAST_INSTANT_TRADE_PAY");
        // 30分钟后自动收单
        aliPay.setTimeout_express(alipayProperties.getTimeoutExpressMin() + "m");
        String json = JSON.toJSONString(aliPay);
        request.setBizContent(json);

        // 调用SDK生成表单
        String form = alipayClient.pageExecute(request).getBody();
        log.debug("支付响应：{}", form);

        return form;
    }

    /**
     * 统一收单交易关闭接口
     * 用于交易创建后，用户在一定时间内未进行支付，可调用该接口直接将未付款的交易进行关闭。
     * 参考：https://opendocs.alipay.com/open/8dc9ebb3_alipay.trade.close?scene=common&pathHash=0c042d2b
     *
     * @param trade_no 支付宝交易号
     * @param out_trade_no 商户订单号
     * 订单支付时传入的商户订单号,和支付宝交易号不能同时为空。 trade_no,out_trade_no如果同时存在优先取trade_no
     * @return
     */
    public boolean close(String trade_no, String out_trade_no) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayProperties.getGatewayUrl(),
                alipayProperties.getAppId(),
                alipayProperties.getAppPrivateKey(),
                alipayProperties.getFormat(),
                alipayProperties.getCharset(),
                alipayProperties.getAlipayPublicKey(),
                alipayProperties.getSignType());

        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", trade_no);
        bizContent.put("out_trade_no", out_trade_no);
        request.setBizContent(bizContent.toString());
        AlipayTradeCloseResponse response = alipayClient.execute(request);
//        if("10000".equals(response.getCode())) {}
        if (response.isSuccess()) {
            log.info("收单成功，单号：{}", trade_no);
            return true;
        } else {
            log.error("收单失败，单号：{}", trade_no);
            return false;
        }
    }
}
